// @ts-nocheck
/**
 * 同步Result类（自带实例方法）
 */
export class Result<T, E> {
    // 私有构造函数，确保只能通过Ok/Err创建实例
    private constructor(
        public readonly isOk: boolean,
        private readonly value: T,
        private readonly error: E
    ) { }

    /**
     * 映射成功值
     */
    map<U>(fn: (value: T) => U | Result<U, any>): Result<U, E> {
        if (!this.isOk) {
            return new Result<U, E>(false, undefined as unknown as U, this.error);
        }
        const mapped = (()=>{
            try {
                return fn(this.value);
            }catch(e){
                return Err(e)
            }
        })() 

        if (mapped instanceof Result) {
            return mapped;
        }

        return Ok(mapped);
    }

    /**
     * 链式处理
     */
    andThen<U, F>(fn: (value: T) => Result<U, F>): Result<U, E | F> {
        if (!this.isOk) {
            return new Result<U, E | F>(false, undefined as unknown as U, this.error);
        }

        try {
            return fn(this.value);
        } catch (err) {
            return new Result<U, E | F>(false, undefined as unknown as U, err as E | F);
        }
    }

    /**
     * 处理错误
     */
    except<U>(fn: (error: E) => U | Result<U, any>): Result<T | U, never> {
        if (this.isOk) {
            return new Result<T | U, never>(true, this.value, undefined as never);
        }

        try {
            const handled = fn(this.error);
            if (handled instanceof Result) {
                return new Result<T | U, never>(handled.isOk, handled.value, handled.error as never);
            }
            return Ok(handled);
        } catch (err) {
            return new Result<T | U, never>(false, undefined as unknown as T | U, err as never);
        }
    }

    /**
     * 提取值
     */
    unwrap(defaultValue: T): T {
        return this.isOk ? this.value : defaultValue;
    }

    /**
     * 转换为Promise<Result>（用于异步处理）
     */
    toPromise(): Promise<Result<T, E>,never> {
        return Promise.resolve(this);
    }

}

/**
 * 为Promise<Result>扩展异步方法
 */
declare global {
    interface Promise<R> {
        isOk(): Promise<boolean>;

        /**
         * 异步map（仅对Promise<Result>有效）
         */
        map<U>(this: Promise<Result<any, any>>, fn: (value: any) => U | Result<U, any>): Promise<Result<U, any>>;

        /**
         * 异步andThen（仅对Promise<Result>有效）
         */
        andThen<U, F>(this: Promise<Result<any, any>>, fn: (value: any) => Result<U, F>): Promise<Result<U, any | F>>;

        /**
         * 异步except（仅对Promise<Result>有效）
         */
        except<U>(this: Promise<Result<any, any>>, fn: (error: any) => U | Result<U, any>): Promise<Result<any | U, never>>;

        /**
         * 异步unwrap（仅对Promise<Result>有效）
         */
        unwrap(this: Promise<Result<any, any>>, defaultValue: any): Promise<any>;
    }
}

/**
 * 实现Promise原型的异步方法
 */
if (!Promise.prototype.isOk) {
    Object.defineProperty(Promise.prototype, 'isOk', {
        value: async function (this: Promise<Result<any, any>>): Promise<boolean> {
            const result = await this;
            return result.isOk;
        }
    });
}

if (!Promise.prototype.map) {
    Object.defineProperty(Promise.prototype, 'map', {
        value: async function <U>(this: Promise<Result<any, any>>, fn: (value: any) => U | Result<U, any>): Promise<Result<U, any>> {
            const result = await this;
            return result.map(fn);
        }
    });
}

if (!Promise.prototype.andThen) {
    Object.defineProperty(Promise.prototype, 'andThen', {
        value: async function <U, F>(this: Promise<Result<any, any>>, fn: (value: any) => Result<U, F>): Promise<Result<U, any | F>> {
            const result = await this;
            return result.andThen(fn);
        }
    });
}

if (!Promise.prototype.except) {
    Object.defineProperty(Promise.prototype, 'except', {
        value: async function <U>(this: Promise<Result<any, any>>, fn: (error: any) => U | Result<U, any>): Promise<Result<any | U, never>> {
            const result = await this;
            return result.except(fn);
        }
    });
}

if (!Promise.prototype.unwrap) {
    Object.defineProperty(Promise.prototype, 'unwrap', {
        value: async function (this: Promise<Result<any, any>>, defaultValue: any): Promise<any> {
            const result = await this;
            return result.unwrap(defaultValue);
        }
    });
}
/**
 * 创建成功的Result
 */
export function Ok<T>(value: T): Result<T, never> {
    return new Result<T, never>(true, value, undefined as never);
}

/**
 * 创建错误的Result
 */

export function From<T, E = any>(fn: () => Promise<T>): Promise<Result<T, E>>;
export function Err<E>(error: E): Result<never, E> {
    return new Result<never, E>(false, undefined as never, error);
}
export function From<T, E = any>(fn: () => T): Result<T, E>;
export function From<T, E = any>(fn: (() => T) | (() => Promise<T>)): Result<T, E> | Promise<Result<T, E>> {
    try {
        const result = fn();
        
        if (result instanceof Promise) {
            return result.then(Ok).catch(Err);
        }
        
        return Ok(result);
    } catch (e) {
        return Err(e as E);
    }
}